package com.windward.vii.web.controller.filter;

import com.alibaba.fastjson.JSON;
import com.windward.vii.common.JsonResult;
import com.windward.vii.common.ResultCode;
import com.windward.vii.service.UserTokenService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class RequestFilter implements Filter {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(RequestFilter.class);

    @Value("${web.filter.login:/v1/api1/*;/v2/api1/*}")
    private String urlPattern;

    @Resource
    UserTokenService userTokenService;

    @Override
    public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
        logger.info("init........");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String token = request.getHeader("token");
        logger.info("token:{}", token);
//        Boolean ignore = false;
//        //ignore
//        List<String> ignores = new ArrayList<String>(){{
//            add("v1/api1/notice/buildingnotice");
//            add("v1/api1/notice/list");
//            add("v1/api1/notice/preferential");
//            add("v1/api1/notice/buildingone");
//        }};
//
//        for(String ig : ignores) {
//            if(request.getServletPath().indexOf(ig)!=-1){
//                ignore = true;
//                break;
//            }
//        }
        if (token == null) {
            response.setHeader("Content-Type", "application/json; charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(new JsonResult(ResultCode.TOKEN_INVALID_CODE, ResultCode.TOKEN_NULL_MSG)));
            response.getWriter().flush();
            return;
        }
        //验证 token
        long uid = userTokenService.getUidByToken(token);
        if(uid <= 0) {
            response.setHeader("Content-Type", "application/json; charset=UTF-8");
            response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(new JsonResult(ResultCode.TOKEN_INVALID_CODE,ResultCode.TOKEN_INVALID_MSG)));
            response.getWriter().flush();
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        logger.info("destroy........");
    }
} 